package com.zdp.demo.utils;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdp.demo.entity.BaseEntity;

import javax.annotation.Nullable;
import java.util.Optional;

public final class PageConvert {

    public static <T> Page<T> convert(BaseEntity baseEntity) {
        Page<T> page = new Page((long) Convert.toInt(baseEntity.getCurrent(), 1), (long) Convert.toInt(baseEntity.getSize(), 10));

        // 1,2,3 -> [1,2,3]
        String[] ascArr = Convert.toStrArray(baseEntity.getAscs());
// ascArr不为null进入ifPresent里面的代码块同时可以把ascArr携带进来
        Optional.ofNullable(ascArr).ifPresent((ascs) -> {
            String[] ascStrings = ascs;
            int strLength = ascs.length;
            for (int i = 0; i < strLength; i++) {
                String asc = ascStrings[i];
                page.addOrder(new OrderItem[]{OrderItem.asc(cleanIdentifier(asc))});
            }
        });

        String[] descArr = Convert.toStrArray(baseEntity.getDescs());
        Optional.ofNullable(descArr).ifPresent((descs) -> {
            String[] descStrings = descs;
            int strLength = descStrings.length;

            for(int i = 0; i < strLength; ++i) {
                String desc = descStrings[i];
                page.addOrder(new OrderItem[]{OrderItem.desc(cleanIdentifier(desc))});
            }
        });

        return page;
    }

    @Nullable
    private static String cleanIdentifier(@Nullable String param) {
        if (param == null) {
            return null;
        } else {
            StringBuilder paramBuilder = new StringBuilder();

            for(int i = 0; i < param.length(); ++i) {
                char c = param.charAt(i);
                if (Character.isJavaIdentifierPart(c)) {
                    paramBuilder.append(c);
                }
            }
            return paramBuilder.toString();
        }
    }
}
